
import 'dart:async';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ConfigHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/Constant.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ImageHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/SpHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/helper/ViewHelper.dart';
import 'package:ysy_flutter_mvvm_yuanxuan/view/login/LoginVM.dart';

typedef IndexCallback =Function (int);
typedef FutureCallback =Future<bool> Function ();

LoginVM registeredVM=LoginVM();

//注册
class RegisteredWidget extends StatefulWidget {

  const RegisteredWidget({Key? key}) : super(key: key);

  @override
  _RegisteredWidgetState createState() => _RegisteredWidgetState();
}

class _RegisteredWidgetState extends State<RegisteredWidget> {

  bool isInputMeet=false;
  bool isSelected=false;
  TextEditingController _phoneController=TextEditingController();
  TextEditingController _pwController=TextEditingController();
  TextEditingController _pw1Controller=TextEditingController();
  TextEditingController _codeController=TextEditingController();

  @override
  void initState() {
    super.initState();
  }
  @override
  void dispose() {
    super.dispose();
    _phoneController.dispose();
    _pwController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Container(
          height: MediaQuery.of(context).size.height,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              //标题栏
              Container(
                  margin: EdgeInsets.fromLTRB(0, 20.h, 0, 0),
                  child: DufTitleBar()),
              Padding(padding: EdgeInsets.fromLTRB(0, 40.h, 0, 0)),
              //登录方式按钮
              TypeWitget(),
              //输入框
              RegisteredEditWidget(_phoneController, _pwController,_pw1Controller,_codeController, (value) {
                var phone = _phoneController.text;
                var code = _codeController.text;
                var pw = _pwController.text;
                var pw1 = _pw1Controller.text;
                isInputMeet=phone.length>=11 && code.length>=4 && pw.length>0 && pw1.length>0;
                setState(() {});
              }, () { //
                var phone = _phoneController.text;
                if(phone.isNotEmpty){
                  registeredVM.onSMSVerCode(phone: phone,type: 2);
                  return Future.value(true);
                }else{
                  showCenterToast("请输入手机号");
                }
                return Future.value(false);
              }),
              //登录按钮
              Container(
                width: double.infinity,
                margin: EdgeInsets.fromLTRB(30.w, 30.h, 30.w, 0),
                child: ElevatedButton(
                  autofocus: true,
                  onPressed: (){
                    if(!isInputMeet){
                      return;
                    }
                    onRegister();
                  },
                  child: Text("注册",style: TextStyle(color: Colors.white,fontSize: 14.sp),),
                  style: ButtonStyle(
                      backgroundColor:MaterialStateProperty.all(Color(isInputMeet?ConstantColors.mainColor:0XFFdddddd)),
                      fixedSize:MaterialStateProperty.all(Size(double.infinity, 44.h)),
                      shape:MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(22.h)))
                  ),
                ),
              ),
              Container(
                alignment: Alignment.bottomCenter,
                padding: EdgeInsets.fromLTRB(24.w, 10.h, 24.w, 32.h),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      padding: EdgeInsets.fromLTRB(0, 0, 6.sp, 0),
                      alignment: Alignment.centerLeft,
                      child: DufCheckbox(value: isSelected, radius: 7.sp,onChanged: (value){
                        isSelected=value==true?true:false;
                        setState(() {});
                      },)
                    ),
                    Container(
                      alignment: Alignment.centerLeft,
                      width: MediaQuery.of(context).size.width-106.w,
                      child: Text.rich(
                        TextSpan(
                            // text: "注册即表示同意",style: TextStyle(fontSize: 12.sp,color: Colors.black),
                            children: [
                              WidgetSpan(child: Text("注册即表示同意",style: TextStyle(fontSize: 12.sp,color: Colors.black),textAlign: TextAlign.left,)),
                              WidgetSpan(child: InkWell(onTap: (){}, child: Text("《用户协议》",style: TextStyle(fontSize: 12.sp,color: Color(0xff0267FF)),textAlign: TextAlign.left,))),
                              WidgetSpan(child: InkWell(onTap: (){}, child: Text("《隐私声明》",style: TextStyle(fontSize: 12.sp,color: Color(0xff0267FF)),textAlign: TextAlign.left,))),
                            ]),
                        softWrap: true,
                        textAlign: TextAlign.left,
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
  //发起注册
  void onRegister(){
    FocusManager.instance.primaryFocus?.unfocus();
    var phone = _phoneController.text;
    if(phone.isEmpty){
      showCenterToast("请输入手机号");
      return;
    }
    var code = _codeController.text;
    if(code.isEmpty){
      showCenterToast("请输入验证码");
      return;
    }
    var pw = _pwController.text;
    if(pw.isEmpty){
      showCenterToast("请输入密码");
      return;
    }
    var pw1 = _pw1Controller.text;
    if(pw1.isEmpty){
      showCenterToast("请再次输入密码");
      return;
    }
    if(pw!=pw1) {
      showCenterToast("两次输入的密码不一致！");
      return;
    }
    if(!isSelected){
      showCenterToast("您尚未同意注册相关条款！");
      return ;
    }
    registeredVM.appRegister(phone: phone, authCode: code, password: pw,requestDone: (){
       if(registeredVM.registerBean!=null){
         Navigator.of(context).pop();
       }
       SPHelper.savePhone(phone);
    });
  }

}

class TypeWitget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 90.sp,
      margin: EdgeInsets.fromLTRB(30.w, 18.h, 0, 0),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
              height: 16.h,
              margin: EdgeInsets.fromLTRB(0.w, 18.h, 0, 0),
              decoration: ShapeDecoration(
                  gradient: LinearGradient(begin: Alignment.bottomRight,end:Alignment.topLeft,colors: [Color(0xffFF905F),Color(0xffFFC194)]),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(8.sp))
                  )
              )
          ),
          Text("手机注册",style: TextStyle(fontSize: 18.sp,color: Color(0xff333333)),textAlign: TextAlign.center,),
        ],
      ),
    );
  }
}


//注册
class RegisteredEditWidget extends StatefulWidget {

  TextEditingController _phoneController; //电话文本框 监听器
  TextEditingController _pwController;//验证码文本框 监听器
  TextEditingController _pw1Controller;//验证码文本框 监听器
  TextEditingController _codeController;//验证码文本框 监听器
  ValueChanged<String>? _onChanged;//文本框 输入触发器
  FutureCallback futureCallback;
  int currentTiming=ConfigHelper.verificationCodeTiming;

  RegisteredEditWidget(this._phoneController, this._pwController,this._pw1Controller,this._codeController,this._onChanged,this.futureCallback);

  @override
  _RegisteredEditWidgetState createState() => _RegisteredEditWidgetState();
}

class _RegisteredEditWidgetState extends State<RegisteredEditWidget> {

  Timer? timer;

  @override
  void initState() {
    super.initState();
  }

  //重新计时
  void newTimer(){
    timer?.cancel();
    widget.currentTiming=ConfigHelper.verificationCodeTiming;
    timer = Timer.periodic(Duration(seconds: 1), (index) {
      widget.currentTiming--;
      if(widget.currentTiming<=0){
        timer?.cancel();
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.fromLTRB(40.w, 40.h, 40.w, 0),
      color: Colors.white,
      child: Column(
        children: [
          Container(
              height: 70.h,
              child: TextField(
                onChanged: widget._onChanged,
                controller: widget._phoneController,
                style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,height: 1.2),
                cursorWidth: 1.5.w,
                cursorColor: Color(ConstantColors.mainColor),
                textAlignVertical:TextAlignVertical.center,
                textInputAction: TextInputAction.next,
                maxLength: 24,
                decoration: InputDecoration(
                  counterText: "",
                  hintText: "请输入手机号",
                  suffixIcon:widget._phoneController.text.isEmpty?null:IconButton(
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      onPressed: (){
                        widget._phoneController.clear();
                      }, icon: Image.asset(assetPath("ic_close_gray_small.png"),height:12.h ,fit: BoxFit.fitHeight,)),
                  hintStyle: TextStyle(color: Color(0xffbbbbbb),fontSize: 14.sp),
                  prefixIcon: Container(
                      width: 90.w,
                      child: Row(
                        children: [
                          Text("中国(+86) ",style: TextStyle(color: Color(0xff333333),fontSize: 14.sp),),
                          Padding(
                            padding: EdgeInsets.fromLTRB(4.w, 0, 4.w, 0),
                            child: Image.asset(assetPath("ic_find_extend1.png"),height: 5.h,fit:BoxFit.fitHeight,),
                          ),
                        ],
                      )),
                  focusedBorder:UnderlineInputBorder(borderSide: BorderSide(color: Color(ConstantColors.mainColor))),
                  border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                  enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                ),
              )),
          Container(
              height: 70.h,
              child: TextField(
                onChanged: widget._onChanged,
                controller: widget._codeController,
                style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,height: 1.2),
                cursorWidth: 1.5.w,
                cursorColor: Color(ConstantColors.mainColor),
                textAlignVertical:TextAlignVertical.center,
                textInputAction: TextInputAction.send,
                maxLength: 10,
                decoration: InputDecoration(
                  counterText: '',
                  hintText: "请输入验证码",
                  suffixIcon:TextButton(
                      style: ButtonStyle(overlayColor:MaterialStateProperty.all(timer?.isActive!=true?Colors.black12:Colors.transparent)),
                      onPressed: (){
                        if(timer?.isActive!=true){
                          var future = widget.futureCallback();
                          future.asStream().listen((event) {
                            if(event){
                              newTimer();
                            }
                          });
                        }
                      },
                      child: Text(timer?.isActive==true?"重新发送(${widget.currentTiming})":"获取验证码",style: TextStyle(fontSize: 12.sp,color: Color(timer?.isActive==true?0xff999999:0xfffF862D)),)),
                  hintStyle: TextStyle(color: Color(0xffbbbbbb),fontSize: 14.sp),
                  focusedBorder:UnderlineInputBorder(borderSide: BorderSide(color: Color(ConstantColors.mainColor))),
                  border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                  enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                ),
              )),
          Container(
              height: 70.h,
              child: TextField(
                onChanged: widget._onChanged,
                controller: widget._pwController,
                style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,height: 1.2),
                cursorWidth: 1.5.w,
                cursorColor: Color(ConstantColors.mainColor),
                textAlignVertical:TextAlignVertical.center,
                textInputAction: TextInputAction.next,
                maxLength: 24,
                obscuringCharacter: "*",
                obscureText: true,
                decoration: InputDecoration(
                  counterText: "",
                  hintText: "请输入密码",
                  suffixIcon:widget._pwController.text.isEmpty?null:IconButton(
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      onPressed: (){
                        widget._pwController.clear();
                      }, icon: Image.asset(assetPath("ic_close_gray_small.png"),height:12.h ,fit: BoxFit.fitHeight,)),
                  hintStyle: TextStyle(color: Color(0xffbbbbbb),fontSize: 14.sp),
                  focusedBorder:UnderlineInputBorder(borderSide: BorderSide(color: Color(ConstantColors.mainColor))),
                  border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                  enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                ),
              )),
          Container(
              height: 70.h,
              child: TextField(
                onChanged: widget._onChanged,
                controller: widget._pw1Controller,
                style: TextStyle(color: Color(0xff333333),fontSize: 16.sp,height: 1.2),
                cursorWidth: 1.5.w,
                cursorColor: Color(ConstantColors.mainColor),
                textAlignVertical:TextAlignVertical.center,
                textInputAction: TextInputAction.next,
                maxLength: 24,
                obscuringCharacter: "*",
                obscureText: true,
                decoration: InputDecoration(
                  counterText: "",
                  hintText: "请输入密码",
                  suffixIcon:widget._pw1Controller.text.isEmpty?null:IconButton(
                      splashColor: Colors.transparent,
                      highlightColor: Colors.transparent,
                      onPressed: (){
                        widget._pw1Controller.clear();
                      }, icon: Image.asset(assetPath("ic_close_gray_small.png"),height:12.h ,fit: BoxFit.fitHeight,)),
                  hintStyle: TextStyle(color: Color(0xffbbbbbb),fontSize: 14.sp),
                  focusedBorder:UnderlineInputBorder(borderSide: BorderSide(color: Color(ConstantColors.mainColor))),
                  border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                  enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffEFF0F2))),
                ),
              )),
        ],
      ),
    );
  }
}